<?php


namespace seecms\lib\provider;

use seecms\db\SeeDbException;
use seecms\See;
use Psr\SimpleCache\InvalidArgumentException;
use seecms\SeeException;

/**
 * @property array|null login
 * @property array|null smtp
 * @property array|null backup
 * @property array|null upload
 * @property array|null site
 */
class General
{
    /**
     * 保存
     * @param string $group
     * @param array $settings
     * @return void
     */
    public function save(string $group, array $settings)
    {
        foreach ($settings as $name => $value) {

            if (is_array($value)) {
                $value = json_encode($value, JSON_UNESCAPED_UNICODE);
            }

            try {
                See::table()->setting->updateOrCreate(compact('group', 'name'), compact('value'));
            } catch (SeeDbException $e) {

            }
        }

        $this->clear($group);
    }

    /**
     * @param $name
     * @return array
     */
    public function get($name): array
    {
        $key = 'seecms_general_setting_group_' . $name;
        $data = See::cache()->get($key);

        if ($data) {
            return $data;
        }

        try {
            $data = See::table()->setting->where('group', $name)->column('value', 'name');
        } catch (SeeDbException $exception) {
            $data = [];
        }

        try {
            $data && See::cache()->set($key, $data);
        } catch (\Psr\Cache\InvalidArgumentException $exception) {
            $data = [];
        }


        return $data ?: [];
    }

    /**
     * @return void
     */
    public function clear($group)
    {
        if ($group === 'all') {
            $groups = ['login', 'smtp', 'database', 'upload', 'website', 'wechat'];
        } else {
            $groups = [$group];
        }

        foreach ($groups as $group) {
            try {
                $key = 'seecms_general_setting_group_' . $group;
                See::cache()->delete($key);
            } catch (InvalidArgumentException $e) {

            }
        }
    }

    /**
     * @param $name
     * @return array
     */
    public function __get($name)
    {
        try {
            $value = $this->get($name) ?? null;
        } catch (\Psr\Cache\InvalidArgumentException|SeeException $e) {
            return [];
        }

        return is_array($value) ? $value : [];
    }
}